const { list, tab, userList } = require('./mock')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
const key = 'erbfwdwqqweqweq'
// TypeScript
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;
// 普通公钥模式
const alipaySdk = new AlipaySdk({
	// 参考下方 SDK 配置
	appId: '2021000119601763',
	privateKey: `MIIEowIBAAKCAQEAw8n+AicnWKCsuW0IaBaWBBU07cMuBLvDPG9AXjSOwIcEH9udgbwvLhYL2FNVL5icv9Dd/VxDBfh6ruNqovhatq1lX8psa32+MiuJbfVqysoxnuGboV9aXfl8XDcrrzW42JVkTzfy73PC6iOeccYH9YFzL8jJdQN4Iov9swAGVA7n87TkI/I+NhI/hz3bC7AXYjF9Ozi+/pXRel/YsptfmmHteSuQ9R1N7q1pQceuF5fSPh3eVEKn94OvO1fzmQdR0uBu3c0RFhWD1WaINsKSsSP0vihDUwNJK74XoTrbZVnvOhdpKTCH8sNqM8ST+M3UZ+WO/Ia1Q1imS1dMG6jM+QIDAQABAoIBAHeR7Kaz8ruVpOa5R+EJqiRkLyblhD0vzlQiPVVLE8NQsZwjK1YH72hd3m4GtoeS1GfwzyHkLqp+za3xBTbyJbRawQZ3QS+EY5uQKyYUM1wVj6hQcBNlgHLT4rcOmocub+0Vj2Ux7hN+xxLnHeSt5D5zCD2uihoEPGIczJt88GB0hi+JqZitGWs+X0voQouPusAfW4F/qN+mgcnxGrnQ/5raWTFOlLPw/uxNdsZTdQ4fjfGTpOkK859uDN9rjxcvacWMRS4QFqg7UZuS1DQ0cKm6jG4PPBZqPf+4fyLQjZYyssbdQ5lxrO9bO8Bw1Pqza+nfUkN5S5Xf2B5MM4D1Y4ECgYEA/2QpVl31YFaKqDVuF6pdExGK8QIuqbOZmSBa5g0+YY9v0QEGJl61HzHfooHVGlrXa/V6+dL1MLFDD6SvWyVjfSIXSJ4shNQ2L7yBdmd/ZTTYMLNEfaIedJCvAgxI2UfwstsDO3VDz90ZSK7h72JGLjjnIhUznu6l5NnPqjHF0A0CgYEAxEF2NX3L1UZHaJZhmwjJbvPrF2XX7A4L634TPtF/n/gNQZhILExhNIlz9F5aevYVNlSzvKpXXOgxS9cuKCsxnWVf7Ym83ZAzLud88QQq11QBU4RxzfG8bf+q2diX2Gt+XM2AfPjrF49YFi/qO4PMolz5b37QaCfnN43ZmBt2yZ0CgYEAyeME5nhKA8kFvSjXia+r+enxOsnt10rZjfnMwXUQrhC0ZLT5hpVxemJzlcQqkLXk+zvH5ftExiQqjhAyasvolL/BRi97o9kZqKzMbqwsQfX/PKhJ6UKh7qV9IxJQ+CptdQW6zWLKo2P1m8ZbZl/6eImU9RVrhCTFUV55UeIcrHUCgYAmJRsWtoahw3EpsODzwzdzq1EsUQ0wwmIquWyALzQBIbNh5nlQst/J2FWDT7uCXsYsszXkG6+zTSYXuZEtGYghMYz9nGHrJpXsLe4o4kh5ZciENR/xiWS4dJL+mIya8fmzi/XHVJJNF/1lApciTjG99Rg+RYW4WNkmARoj6GKkOQKBgHWgFL+qxVZra8m13QA0iKhHcWEYmqG+GnhNzBu/EbEnX4Zc1wxI/uC+o7K+Q4L8K4kVJJyHAxCZsPPS1UhPzCAR0lyCCpl/xmmsPcXDWnxnPkZMlujwAHDKmwnK1nAu0lwC6XBJhJYQ/WDRz0apM38QMNL5SmdYfIgBEnooo2np`,
	gateway: 'https://openapi.alipaydev.com/gateway.do'
});


module.exports = app => {
	app.use(bodyParser.json())
	// 首页列表
	app.get('/api/list', (req, res) => {
		const { pageSize = 10, pageCode = 1 } = req.query;
		if (pageSize * pageCode <= list.length) {
			res.send({
				code: 200,
				data: {
					data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize).map(v => {
						const { body: { items: [item] } } = v
						const { label_title, id, product_price, product_name, url } = item
						return {
							id,
							image: url,
							title: product_name,
							word: label_title,
							price: product_price
						}
					}),
					total: list.length,
				},
				message: '数据获取成功'
			})
		} else {
			res.send({
				code: 204,
				message: '没有更多数据了'
			})
		}
	})
	// 分类列表
	app.get('/api/tab', (req, res) => {
		res.send({
			code: 200,
			data: tab,
			message: '数据获取成功'
		})
	})

	app.post('/api/login', (req, res) => {
		const { username, password } = req.body;
		const user = userList.find(v => v.username === username && v.password === password);
		if (user) {
			res.send({
				code: 200,
				message: '登录成功， 欢迎' + user.nickname,
				data: {
					token: JWT.sign({
						username: user.username,
						nickname: user.nickname,
						addressList: user.addressList,
						orderList: user.orderList,
						avator: user.avator,
						id: user.id
					}, key),
					username: user.username,
					nickname: user.nickname,
					addressList: user.addressList,
					orderList: user.orderList,
					avator: user.avator,
					id: user.id
				}
			})
		} else {
			res.send({
				code: 403,
				message: '账户密码错误， 请重新登录',
			})
		}
	})

	// 支付宝支付接口
	app.post('/api/pay/', async (req, res) => {
		const { id, price, title } = req.body;
		// 调用支付接口

		const formData = new AlipayFormData();
		// 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
		formData.setMethod('get');

		formData.addField('returnUrl', 'http://localhost:3000/pay/result');
		// get method 需要确保 field 都是字符串
		formData.addField('bizContent', JSON.stringify({
			outTradeNo: id,
			totalAmount: price,
			subject: title,
		}));

		try {
			const result = await alipaySdk.exec(
				'alipay.trade.wap.pay',
				{},
				{ formData: formData },
			);

			res.send({
				code: 200,
				data: result
			})
		} catch (error) {
			res.send({
				code: 400,
				data: error
			})
		}
	})

	app.get('/api/order/query', async (req, res) => {
		const { out_trade_no, trade_no } = req.query
		console.log(out_trade_no, trade_no)
		try {
			const result = await alipaySdk.exec(
				'alipay.trade.query',
				{
					bizContent: {
						out_trade_no, trade_no
					},
				}
			);
			const { code, tradeStatus } = result;
			if (code === '10000') {
				switch (tradeStatus) {
					case 'WAIT_BUYER_PAY':
						res.send({
							code: 200,
							message: '交易创建，等待买家付',
							data: result
						});
						return
					case 'TRADE_CLOSED':
						res.send({
							code: 200,
							message: '未付款交易超时关闭，或支付完成后全额退款',
							data: result
						});
						return
					case 'TRADE_SUCCESS':
						res.send({
							code: 200,
							message: '交易支付成功',
							data: result
						});
						return
					case 'TRADE_FINISHED':
						res.send({
							code: 200,
							message: '交易结束，不可退款',
							data: result
						});
						return
				}
			} else if (code === '40004') {
				res.send({
					code: 404,
					message: '交易不存在'
				})
			}


		} catch (error) {
			res.send({
				message: '查询失败',
				error
			})
		}


	})
}